package service

import (
	"context"
	"errors"
	"fmt"
	"time"
	"video-service/basic/config"
	__ "video-service/basic/proto"
	"video-service/model"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedVideoServer
}

// VideoByCreate 发布
func (s *Server) VideoByCreate(_ context.Context, in *__.VideoByCreateReq) (*__.VideoByCreateResp, error) {
	var user model.Users
	userId := in.UserId
	config.DB.Where("id = ?", userId).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("用户不存在")
	}
	if user.Role != 2 {
		return nil, errors.New("管理员审核")
	}
	videos := model.Videos{
		UserId:           int(userId),
		ClassificationId: int(in.ClassificationId),
		AreaId:           int(in.AreaId),
		YearId:           int(in.Year),
		Title:            in.Title,
		Describe:         in.Describe,
		VideoUrl:         in.VideoUrl,
		Episode:          int(in.Episode),
		EpisodeCount:     int(in.EpisodeCount),
		PlayCount:        int(in.PlayCount),
	}
	config.DB.Create(&videos)
	return &__.VideoByCreateResp{
		VideoId: int64(videos.ID),
	}, nil
}

// ExamineByUpdate 审核
func (s *Server) ExamineByUpdate(_ context.Context, in *__.ExamineByUpdateReq) (*__.ExamineByUpdateResp, error) {
	var user model.Users
	userId := in.UserId
	config.DB.Where("id = ?", userId).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("用户不存在")
	}
	var video model.Videos
	videoId := in.VideoId
	err := video.VideoViewID(config.DB, int(videoId))
	if err != nil {
		return nil, err
	}
	if video.ID == 0 {
		return nil, errors.New("视频不存在")
	}
	config.DB.Updates(&model.Videos{EpisodeStatus: video.EpisodeStatus})
	examines := model.Examines{
		UserId:         int(userId),
		VideoId:        int(videoId),
		ExamineStatus:  int(in.ExamineStatus),
		ReviewRejected: in.ReviewRejected,
	}
	config.DB.Create(examines)

	return &__.ExamineByUpdateResp{
		ExamineId: 0,
	}, nil
}

// VideoByList 列表
func (s *Server) VideoByList(_ context.Context, in *__.VideoByListReq) (*__.VideoByListResp, error) {
	var video []model.Videos
	//list := video.VideoByList(config.DB, int(in.Page), int(in.PageSize))
	page := in.Page
	pageSize := in.PageSize
	if page <= 0 {
		page = 1
	}

	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 2
	}
	var items []*__.VideoListItem
	offset := (page - 1) * pageSize

	config.DB.Offset(int(offset)).Limit(int(pageSize)).Find(&video)
	for _, v := range video {
		sprintf := fmt.Sprintf("list%s", v.Title)
		config.RDB.Set(context.Background(), sprintf, items, time.Hour*24)
		items = append(items, &__.VideoListItem{
			UserId:           int64(v.UserId),
			ClassificationId: int64(v.ClassificationId),
			AreaId:           int64(v.AreaId),
			Year:             int64(v.YearId),
			Title:            v.Title,
			Describe:         v.Describe,
			VideoUrl:         v.VideoUrl,
			Episode:          int64(v.Episode),
			EpisodeCount:     int64(v.EpisodeCount),
			PlayCount:        int64(v.PlayCount),
		})

	}

	return &__.VideoByListResp{
		List: items,
	}, nil

}

// EpisodesByCreate 剧集
func (s *Server) EpisodesByCreate(_ context.Context, in *__.EpisodesByCreateReq) (*__.EpisodesByCreateResp, error) {
	var video model.Videos
	videoId := in.VideoId
	err := video.VideoViewID(config.DB, int(videoId))
	if err != nil {
		return nil, err
	}
	if video.ID == 0 {
		return nil, errors.New("视频不存在")
	}
	//var episode model.Episodes
	//err = episode.EpisodesViewID(config.DB, episode.Id)
	//if err != nil {
	//	return nil, err
	//}
	episodes := model.Episodes{
		VideoId:      int(videoId),
		Title:        in.Title,
		Describe:     in.Describe,
		VideoUrl:     in.VideoUrl,
		Episode:      int(in.Episode),
		EpisodeCount: int(in.EpisodeCount),
		Duration:     int(in.Duration),
		PlayCount:    int(in.PlayCount),
		Collect:      int(in.Collect),
	}
	err = config.DB.Create(&episodes).Error
	if err != nil {
		return nil, err
	}
	config.DB.Updates(&model.Videos{
		EpisodeStatus: 2,
	})
	return &__.EpisodesByCreateResp{
		EpisodesId: int64(episodes.Id),
	}, nil
}
func (s *Server) DramaRecordDetails(_ context.Context, in *__.DramaRecordDetailsReq) (*__.DramaRecordDetailsResp, error) {
	var records []model.DramaRecord
	page := in.Page
	pageSize := in.PageSize
	if page <= 0 {
		page = 1
	}

	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 5
	}
	var items []*__.DramaRecordDetails
	offset := (page - 1) * pageSize
	config.DB.Offset(int(offset)).Limit(int(pageSize)).Find(&records)
	for _, r := range records {
		items = append(items, &__.DramaRecordDetails{
			DramaId:   int64(r.ID),
			VideoId:   int64(r.VideoId),
			ExamineId: int64(r.EpisodeId),
			Duration:  int64(r.Duration),
			PlayCount: int64(r.PlayCount),
			Collect:   int64(r.Collect),
		})
	}
	return &__.DramaRecordDetailsResp{
		List: items,
	}, nil
}
